package com.jl.juc.atomic.aba;

import com.jl.juc.atomic.Person;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 自旋锁会引入ABA问题：
 *
 *  变量 X = 5；
 *
 *  线程1读取到变量的值为5，
 *  线程2读取到变量的值为5，然后更新为6
 *  线程3读取到变量的值为6，然后更新为5
 *  线程1发现自己去取的值和内存中的值还是5，则更新为7
 *
 * 期间线程1并不知道，变量经过了 线程2和线程3的修改
 *
 */
public class ABADemo2AtomicStampedReference {


    public static void main(String[] args) {

        Person person = new Person("郭靖", 25);
        AtomicStampedReference<Person> atomicStampedReference = new AtomicStampedReference<>(person, 1);
        System.out.println(atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());

        Person person2 = new Person("李逍遥", 30);
        boolean b = atomicStampedReference.compareAndSet(person, person2, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
        System.out.println(b +"\t" +atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());

        boolean b1 = atomicStampedReference.compareAndSet(person2, person, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
        System.out.println(b1 +"\t" +atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());
    }

}
